<template>
  <el-card class="account-container">
    <h1 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 26px; color: #615f5f">仪表盘</h1>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-card class="box-card" shadow="hover" style="background-color: #041cf4" body-style="background-color: white">
            <template #header>
              <div class="card-header" style="line-height: 20px">
                <el-icon color="#ffffff" size="20px"><UserFilled /></el-icon>
                <span style="color: white; font-weight: bold; font-size: 20px;">管理员人数</span>
              </div>
            </template>
            <div style="font-size: 26px; color: #615f5f">{{admin_num}}人</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="hover" style="background-color: #ff0707" body-style="background-color: white">
            <template #header>
              <div class="card-header" style="line-height: 20px">
                <el-icon color="#ffffff" size="20px"><InfoFilled /></el-icon>
                <span style="color: white; font-weight: bold; font-size: 20px;">用户待审核</span>
              </div>
            </template>
            <div style="font-size: 26px; color: #615f5f">{{user_num}}条</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="hover" style="background-color: #951af2" body-style="background-color: white">
            <template #header>
              <div class="card-header" style="line-height: 20px">
                <el-icon color="#ffffff" size="20px"><Comment /></el-icon>
                <span style="color: white; font-weight: bold; font-size: 20px;">菜品待审核</span>
              </div>
            </template>
            <div style="font-size: 26px; color: #615f5f">{{dish_num}}项</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="hover" style="background-color: #fb6b4a" body-style="background-color: white">
            <template #header>
              <div class="card-header" style="line-height: 20px">
                <el-icon color="#ffffff" size="20px"><Menu /></el-icon>
                <span style="color: white; font-weight: bold; font-size: 20px;">今日订单数</span>
              </div>
            </template>
            <div style="font-size: 26px; color: #615f5f">{{order_num}}条</div>
          </el-card>
        </el-col>
      </el-row>
    <el-divider />
    <h2 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 21px; color: #615f5f">每日订单数量</h2>
    <div id="chart">
    </div>
    <h2 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 21px; color: #615f5f">每日总收入表</h2>
    <div id="chart-for-all"></div>
    <h2 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 21px; color: #615f5f">店铺收入排名</h2>
    <el-row :gutter="12">
      <el-col :span="12">
        <el-card shadow="hover">
          <h2 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 14px; color: #615f5f">{{currentMerchantName}}店铺收入表</h2>
          <div id="chart-for-merchant"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <el-table :data="tableData" style="width: 100%" max-height="350">
            <el-table-column prop="merchantName" label="名称" width="190" />
            <el-table-column prop="amount" label="今日总收入" width="190" />
            <el-table-column prop="status" label="状态" width="190" >
              <template #default="scope">
                <el-text class="mx-1" :hidden="!(getStatus(scope.$index)===1)" type="success">营业中</el-text>
                <el-text class="mx-1" :hidden="!(getStatus(scope.$index)===0)" type="warning">休息中</el-text>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="Operations" width="190">
              <template #default="scope">
                <el-button
                    link
                    type="primary"
                    size="small"
                    @click.prevent="checkItemNum(scope.$index)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import ApexCharts from 'apexcharts';
import {onMounted, ref} from "vue";
import {searchMerchants} from "@/api/merchant";
import {
  countAdmin,
  countDish,
  countTodayMoney,
  countUser,
  getMerchantDaysMoney,
  getMerchantOrderByMoney,
  listTodayOrders
} from "@/api/counter";
import {Comment, UserFilled} from "@element-plus/icons-vue";

// 获取今天的时间
const currentDate = new Date();


const admin_num = ref(0);

const dish_num = ref(0);

const user_num = ref(0);

const order_num = ref(0);

const order_list = ref([]);

const tableData = ref([]);

const currentMerchantName = ref();

const daysToSubtract = ref(15); // 查询10天内的数据做为输入

const daysToSubtractForMoney = ref(15); // 查询15天内的收入

const daysToSubtractForMerchant = ref(7); // 查询每个商家最近一周的收入情况列表
// 当前的merchant
const currentMerchant = ref({});
// 商家表格数据对象
const merchantChartData = ref({
  all_array: [],
  finish_array: [],
  categories: [],
});
// 总收入的列表
const moneyChartDate = ref({
  money_list: [],
  categories: []
});
// 指定商家在十天内的收入
const merchantMoneyChartData = ref({
  money_list: [],
  categories: []
})
// 查询状态
const getStatus = (index) => {
  return tableData.value[index].status;
}
// 制作订单数量统计表格
const makeOrderNumberChart = () => {

  const options = {
    series: [{
      name: '所有订单',
      data: merchantChartData.value.all_array
    }, {
      name: '已完成订单',
      data: merchantChartData.value.finish_array
    }],
    chart: {
      height: 350,
      type: 'area'
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'smooth'
    },
    xaxis: {
      type: 'datetime',
      categories: merchantChartData.value.categories
    },
    tooltip: {
      x: {
        format: 'dd/MM/yy HH:mm'
      },
    },
  };

  const chart = new ApexCharts(document.querySelector("#chart"), options);
  chart.render();
}
// 制作商家所有的收入表格
const makeMerchantChart = () => {
  const options = {
    series: [{
      name: "Desktops",
      data: moneyChartDate.value.money_list
    }],
    chart: {
      height: 350,
      type: 'line',
      zoom: {
        enabled: false
      }
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'straight'
    },
    title: {
      text: 'Product Trends by Month',
      align: 'left'
    },
    grid: {
      row: {
        colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
        opacity: 0.5
      },
    },
    xaxis: {
      categories: moneyChartDate.value.categories,
    }
  };

  const chart = new ApexCharts(document.querySelector("#chart-for-all"), options);
  chart.render();
}
// 制作商家排名显示表格
const makeMerchantRankingChart = () => {
  const options = {
    series: [{
      name: 'Net Profit',
      data: merchantMoneyChartData.value.money_list
    }],
    chart: {
      type: 'bar',
      height: 350
    },
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: '55%',
        endingShape: 'rounded'
      },
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      show: true,
      width: 2,
      colors: ['transparent']
    },
    xaxis: {
      categories: merchantMoneyChartData.value.categories,
    },
    yaxis: {
      title: {
        text: '￥(元)'
      }
    },
    fill: {
      opacity: 1
    },
    tooltip: {
      y: {
        formatter: function (val) {
          return val + "元"
        }
      }
    }
  };
  // 获取要清除的图表容器元素
  const chartContainer = document.querySelector("#chart-for-merchant");
  document.getElementById("chart-for-merchant").innerHTML = "";
  // 检查容器中是否存在现有的图表实例
  const chart = new ApexCharts(chartContainer, options);
  chart.render();
}
// 选择对应的商家查询相关的表格
const checkItemNum = async (index) => {
  currentMerchant.value = tableData.value[index].merchantId;
  currentMerchantName.value = tableData.value[index].merchantName;
  await getMerchantDaysMoney({
    merchantId: currentMerchant.value,
    time: currentDate.format("yyyy-MM-dd hh:mm:ss"),
    day: daysToSubtractForMerchant.value
  }).then((res) => {
    merchantMoneyChartData.value.money_list = res.data.moneyList;
    for(let item in res.data.timeList) {
      res.data.timeList[item] = new Date(res.data.timeList[item]).format("MM-dd");
    }
    merchantMoneyChartData.value.categories = res.data.timeList;
  });
  // 重新渲染
  makeMerchantRankingChart();
}
// 开局三个表格
onMounted(async () => {
  // 获取今天的时间
  const currentDate = new Date();
  const timeForm = ref({time: currentDate.format("yyyy-MM-dd hh:mm:ss")});
  // 一开始的时候会check一下所有的商家(按照顺序，从大到小)
  getMerchantOrderByMoney(timeForm.value).then((res) => {
    tableData.value = res.data;
  }).then(() => {
    // 然后默认将当前商家设置为收益最大的那个给之后查询
    currentMerchant.value = tableData.value[0].merchantId;
    currentMerchantName.value = tableData.value[0].merchantName;
  })
  // 查询四个数字count
  countUser().then((res) => {
    user_num.value = res.data;
  });
  countDish().then((res) => {
    dish_num.value = res.data;
  });
  countAdmin().then((res) => {
    admin_num.value = res.data;
  });
  // 列出来今天所有的订单,计算今日订单数
  listTodayOrders({time: currentDate.format("yyyy-MM-dd hh:mm:ss")}).then((res) => {
    order_list.value = res.data;
    if (res.data == null) order_num.value = 0;
    else order_num.value = res.data;
  });
  // 查询图表的数据
  for (let item = daysToSubtract.value; item >= 0; item--) {
    const item_time =  new Date(currentDate.getTime() - item * 24 * 60 * 60 * 1000).format('yyyy-MM-dd hh:mm:ss');
    await listTodayOrders({time: item_time}).then((res) => {
      merchantChartData.value.all_array.push(res.data);
      merchantChartData.value.categories.push(item_time);
    });
  }
  // 查询图表的数据
  for (let item = daysToSubtract.value; item >= 0; item--) {
    await listTodayOrders({time: new Date(currentDate.getTime() - item * 24 * 60 * 60 * 1000).format('yyyy-MM-dd hh:mm:ss')}).then((res) => {
      merchantChartData.value.finish_array.push(res.data);
    });
  }
  // 查询图表中的money数据
  for (let item = daysToSubtractForMoney.value; item >= 0; item--) {
    const item_time = new Date(currentDate.getTime() - item * 24 * 60 * 60 * 1000).format('yyyy-MM-dd hh:mm:ss');
    await countTodayMoney({time: item_time}).then((res) => {
      moneyChartDate.value.money_list.push(res.data);
      moneyChartDate.value.categories.push(new Date(currentDate.getTime() - item * 24 * 60 * 60 * 1000).format('MM-dd'));
    });
  }
// 查询今天以及前几天的指定merchant的money数组还有time数组
  await getMerchantDaysMoney({
    merchantId: currentMerchant.value,
    time: currentDate.format("yyyy-MM-dd hh:mm:ss"),
    day: daysToSubtractForMerchant.value
  }).then((res) => {
    merchantMoneyChartData.value.money_list = res.data.moneyList;
    for(let item in res.data.timeList) {
      res.data.timeList[item] = new Date(res.data.timeList[item]).format("MM-dd");
    }
    merchantMoneyChartData.value.categories = res.data.timeList;
  });
  // 制作表格
  makeOrderNumberChart();
  makeMerchantChart();
  makeMerchantRankingChart();
})
</script>
<style scoped>
.course {
  font-weight: bold;
  display: inline-block;
}
.course li {
  line-height: 36px;
  color: #409eff;
  cursor: pointer;
}
</style>
